<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods,i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <!-- 为 my-goods 组件 动态绑定 goods 属性的值-->
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>
<script>
  export default {
    data() {
      return {
        goods_id : '',
        //请求参数对象
        queryObj: {
          query: '',
          cid: '',
          pagenum:1,
          pagesize:10
        },
        total: 0,
        //商品列表数据
        goodsList: [],
        // 节流阀
        isLoading: false,
    };
  },
    onLoad(options) {
      // this.queryObj.query = options.query || ''
      // this.queryObj.cid = options.cid || ''
      this.goods_id = options.cateId || options.homeId
      console.log(this.goods_id)
      
      //获取商品列表数据
      this.getGoodsList()
    },
    methods:{
      // 获取商品列表数据的方法
      getGoodsList(cb){
        if(!this.goods_id) return uni.$showMsg("goods_id获取失败")
        // // 获取db引用
        const db = uniCloud.database() //代码块为cdb
        // 使用uni-clientDB
        db.collection('goodslist_data')
          .where(`'goodslist_id == "${this.goods_id}" '`)
        	.get() 
          .then((res)=>{ 
            // res 为数据库查询结果 
            console.log(res.result)
            this.goodsList = res.result.data[0].goods
            this.total = res.result.data[0].total
          }).catch((err)=>{
            console.log(err.code); // 打印错误码
        		console.log(err.message); // 打印错误内容
          })
        cb && cb()
      },
      UpdateData(){
        this.isLoading = true
        uni.showLoading({
           title:'数据加载中...',
           duration: 1000
         })
        const timer = setTimeout(()=>{
          this.goodsList = [...this.goodsList,...this.goodsList] 
          this.isLoading = false
          clearTimeout(timer)
        },1000)
      },
      //点击跳转到商品详情页面
      gotoDetail(goods){
        uni.navigateTo({
          url:'/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      },
    },
    onReachBottom() {
      //判断数据加载数是
      if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕')
      //判断当前是否在请求数据，防止下拉触发多次请求
      if(this.isLoading) return
      //让页码值自增+1
      this.queryObj.pagenum++
      this.UpdateData()
    },
    //下拉刷新的事件
    onPullDownRefresh(){
      //1.重置关键数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isLoading = false
      this.goodsList = []
      
      //2. 重新发起请求
      this.getGoodsList(() => uni.stopPullDownRefresh())
    },
  }
</script>

<style lang="scss">
</style>
